package com.tim;

import com.tim.helper.DubboHelper;
import com.tim.helper.analysis.xssd.XssdService2Postman;
import com.tim.helper.file.FindCallFile;
import com.tim.helper.inactive.postman.ControllerClass2Postman;
import com.tim.helper.sql.GenEntity;
import com.tim.helper.sql.TableHelper;
import com.tim.helper.string.EnumClassHelper;
import com.tim.helper.string.CodeGen;
import com.tim.third.annotation.CheckAnnotation;
import com.tim.third.annotation.RespSerialize;
import com.tim.util.StringAnalysisUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.maven.model.Dependency;
import org.apache.maven.model.Model;
import org.apache.maven.model.io.xpp3.MavenXpp3Reader;
import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 功能流程：
 * 1，分析功能流程，梳理接口、表
 * 2，建表、接口(基本接口 AcRiderLevelMisService)
 * 3，genEntityAndMapper生成实体、mapper
 * 4，genManagerImplSwaggerFile生成实现类、manager、swagger接口
 * 5，代码逻辑。
 * 6，genPostman生成postman测试。
 *
 * 查询表所在的库
 * SELECT * FROM mysql.`innodb_table_stats` where table_name like CONCAT('%','','%');
 *
 *
 */
public class MainHelper {
	public static final String OUTPUT_DIR = "C:/aa";

	public void helper() throws IOException {
		EnumClassHelper enumClassHelper;// 枚举类工具
		EntityHelper entityHelper;// req、resp、do类工具，字符串-变量互转，转json；测试结果表格
		SqlHelper sqlHelper;// sql工具，req、resp转为对应字段、条件；打印测试动态sql
		StringHelper strHelper;// 字符串工具；打印日志、密码；处理重复信息
		DubboHelper dubboHelper;
		FindCallFile findCallFile;// 查找mapper调用的文件
		new XssdService2Postman().service2Postman();// 生成postman测试
	}

	public void newFunchelperRoute() throws Exception{
		// 阅读原型，逻辑梳理(目的，主流程、场景，状态变化)。对比竞品

		// 整理表结构，建表。idea translate插件翻译

		// 生成实体类、mapper、xml
		new GenEntity().genEntityAndMapper();

		// 输出crud 服务接口；controller、service
		printService();

		// 生成枚举类
		new EnumClassHelper().genEnumByInfo();

		// 生成实现类、manager、swagger
		genImplManagerSwaggerFile();

		// 生成请求/返回实体；查询字段、动态条件；动态sql字段检测
		new EntityHelper().genReqRespByInfo();
		new SqlHelper().printSelectByResp();
		new SqlHelper().printConditionByReq();
		new SqlHelper().printSimpleDynamicSql();

		// 参数校验；返回序列化
		CheckAnnotation checkAnnotation;
		RespSerialize respSerialize;

		// dubbo直调测试、单元测试、postman测试
		DubboHelper dubboHelper;
		new XssdService2Postman().service2Postman();
		ControllerClass2Postman c1;
	}

	public void oldFunchelperRoute() throws Exception{

		// 生成postman测试。熟悉相关接口、业务流程；
		// app端必须考虑新旧接口兼容
		ControllerClass2Postman c1;

		// 查找table，并构建powerDesigner导入文件。
		new TableHelper().searchTable();

		// 查找修改数据库表的java类
		new FindCallFile().findJavaCall();
		new FindCallFile().findXmlCall();

		// 动态sql测试
		new SqlHelper().printSimpleDynamicSql();

	}

	@Test
	public void printInstallCmd() throws Exception {
		String project = "E:\\gitlab\\xqxc\\plat\\plat-admin-mis\\plat-admin-mis-impl" +
				"" +
				"" +
				"";
		// 1，读取、解析pom文件；拼接依赖
		project = project.trim();
		project = project.endsWith("\\")||project.endsWith("/") ? project : project+"/";
		String pomPath = project + "pom.xml";
		Model pomModel = new MavenXpp3Reader().read(new FileReader(pomPath));

		// 2，plat开头的依赖；-f指定路径。
		// 打开terminal，执行命令
		pomModel.getDependencies().stream()
				.map(Dependency::getArtifactId)
				.filter(e -> e.startsWith("plat-"))
				.map(e->e.endsWith("-api")?e.replace("-api", "/")+e:e)
				.forEach(e -> System.out.println(String.format("mvn clean install -DskipTests -f plat/%s/pom.xml", e)));
	}

	/**
	 * 输出crud 服务接口
	 */
	@Test
	public void printService() throws Exception {
		String tableName = "lessee_shop_info";
		String append = "";// 接口名拼接； Mis  Inner
		String tableDesc = "租户部门店铺信息表";// 表注释
		int type = Type.T3;// 0每日说 1懒猪 2山海平店绩 3富民

		// 转换名称
		tableName = tableName.trim().replaceAll("_info", "");
		tableName = StringAnalysisUtil.toPascal(tableName);
		tableDesc = tableDesc.endsWith("表") ? tableDesc.substring(0, tableDesc.length()-1) : tableDesc;
		String template = CodeGen.ServiceTemplate.getTemplate(type);
		String interfaceName = tableName + append;

		// 输出
		String content = template.replaceAll("INTERFACE_NAME", interfaceName)
				.replaceAll("TABLE_NAME", tableName)
				.replaceAll("TABLE_DESC", tableDesc);
//		System.out.println(content);
		Files.write(Paths.get(OUTPUT_DIR, interfaceName+"Service.java"), content.getBytes(StandardCharsets.UTF_8));

	}


	@Test// 生成impl、manager、swagger
	public void genImplManagerSwaggerFile() throws Exception {
		// Service文件绝对路径，优先读文件，其次设置的content
		String serviceFilePath = "C:\\project\\shanhaiping\\smart-hospital\\src\\main\\java\\com\\shanhaiping\\smarthospital\\common\\service\\RedisService.java" +
				"" +
				"";
		serviceFilePath=serviceFilePath.trim();
		// swagger最后生成，防止类名、方法名、参数变更的错误
		int type = Type.T3;// 0每日说 1懒猪 2山海平店绩 3富民

		// group、输出路径；通常不变
		String pathAppend = "";
		pathAppend = "";
		String destProject = OUTPUT_DIR;// 输出路径
		System.out.println(Paths.get(destProject));

		// 读入content，解析pkgName
		String content = " ";
		String srcFileName = "";
		if(StringUtils.isNotBlank(serviceFilePath)){
			// 路径优先
			int end = serviceFilePath.lastIndexOf('\\');
			srcFileName = serviceFilePath.substring(end+1, serviceFilePath.lastIndexOf('.'));
			content = Files.readAllLines(Paths.get(serviceFilePath))
					.stream()
					.map(item->item+"\n")
					.collect(Collectors.joining());

		}

		// impl
		String implFileName = CodeGen.Printer.getImplName(srcFileName);
		List<String> implContent = CodeGen.Printer.getImpl(type).getContent(content, type);
		writeFile(destProject, implFileName, implContent);

		// manager
		String managerFileName = CodeGen.Printer.getManagerName(srcFileName);
		List<String> managerContent = CodeGen.Printer.getManager(type).getContent(content, type);
		writeFile(destProject, managerFileName, managerContent);

		// controller
		String controllerFileName = CodeGen.Printer.getControllerName(srcFileName);
		List<String> swaggerContent = CodeGen.Printer.getSwagger(type, pathAppend).getContent(content, type);
		writeFile(destProject, controllerFileName, swaggerContent);
	}

	private void writeFile(String destProject, String fileName, List<String> content) throws IOException {
		if(!fileName.endsWith(".java")){
			fileName = fileName+".java";
		}
		String collect = content.stream().collect(Collectors.joining("\n"));
    	collect = collect.replaceAll("[\n]{2,}import ", "\nimport ")
			.replaceAll("[\n]{2,}", "\n\n");
//    	System.out.println(collect);
		Files.write(Paths.get(destProject, fileName), Arrays.asList(collect));
		System.out.println("--------------------------------------------------------------------");
	}

	/**   
	 * 0每日说 1懒猪 2山海平店绩 3富民
	 */       
	public interface Type {
		int T0 = 0;
		int T1 = 1;
		int T2 = 2;
		int T3 = 3;
		int T4 = 4;
	}

}
